package com.element.security.resource.handler;

import com.common.core.exception.code.SecurityErrorCode;
import com.common.core.results.VoidResult;
import com.element.security.utils.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 它负责启动未经过身份验证的用户的身份验证过程(当他们试图访问受保护的资源）
 *
 * @auther zhangwj
 * @date 2021/3/18 下午1:47
 */
public class GoAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException e) throws IOException {
        if (e instanceof InsufficientAuthenticationException) {
            logger.error("InsufficientAuthenticationException异常,请求路径:{},异常信息:", request.getServletPath(), e);
            ResponseUtil.writeJson(response, VoidResult.failed(SecurityErrorCode.A_INSUFFICIENT_AUTHENTICATION_ERROR));
        } else {
            logger.error("AuthenticationException异常,请求路径:{},异常信息:", request.getServletPath(), e);
            ResponseUtil.writeJson(response, VoidResult.failed(SecurityErrorCode.A_CANNOT_ACCESS));
        }
    }
}
